package com.rimi.servlet;

import com.alibaba.excel.EasyExcel;
import com.rimi.bean.JsonResult;
import com.rimi.bean.User;
import com.rimi.listener.ExcelInputListener;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author chengliang
 * 创建时间 2020/3/26 9:31
 */
@WebServlet("/excelinput")
public class ExcelInputServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        // text/html
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //实例化对象
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        try {
            //通过fileupload 去解析request对象
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                //找到文件
                if(!fileItem.isFormField()){
                    //获取文件内容
                    InputStream inputStream = fileItem.getInputStream();
                    //读取excel
                    EasyExcel.read(inputStream, User.class, new ExcelInputListener()).sheet().doRead();
                    out.write(JsonResult.SUCCESS().toJson());
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
            System.out.println("文件上传失败");
            out.write(JsonResult.ERROR().toJson());
        }
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
